package com.shanghaionstar.discover.charge.adapter;

import android.animation.ValueAnimator;
import android.content.Context;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.onstar.cn.common.util.HacksUtils;
import com.onstar.cn.common.util.StringUntil;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.base.CommonAdapter;
import com.onstar.cn.framework.base.CommonViewHolder;
import com.onstar.cn.weight.CustomImageView;
import com.onstar.cn.weight.wheel.adapters.AbstractWheelTextAdapter;
import com.onstar.cn.weight.wheel.views.OnWheelChangedListener;
import com.onstar.cn.weight.wheel.views.OnWheelScrollListener;
import com.onstar.cn.weight.wheel.views.WheelView;
import com.shanghaionstar.R;
import com.shanghaionstar.discover.charge.model.ChargeModeTimeItem;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Rengui Lu on 2016/7/27.
 */
public class ChargeModeTimeAdapter extends CommonAdapter<ChargeModeTimeItem> {
     public boolean clicked;
    /**
     * 标示收起或者展开的Item标示
     */
    public int retractPosition = -1, collapsePosition = -1;
    private int wvHeight;
    public boolean doubleAnim;

    private final int maxTextSize = 24;
    private final int minTextSize = 14;

    private int[] SHADOWS_COLORS = new int[]{0xffffff, 0xffffff, 0xffffff};

    private class ViewHolder extends CommonViewHolder {
        @FindViewById
        CustomImageView charge_mode_time_top_iv1;
        @FindViewById
        TextView charge_mode_time_top_tv1, charge_mode_time_top_tv2;
        // @FindViewById
        // TextView cancle_tv, confirm_tv;
        @FindViewById
        RelativeLayout charge_mode_time_top_layout;
        @FindViewById
        WheelView charge_mode_time_wv_hour, charge_mode_time_wv_minute;
        @FindViewById
        LinearLayout charge_mode_time_wv_layout;
        @FindViewById
        View charge_mode_time_top_bottom_line;

        CalendarTextAdapter mHourAdapter;
        CalendarTextAdapter mMinuteAdapter;
        String selectHour;
        String selectMinute;
        ArrayList<String> arry_hours = new ArrayList<String>();
        ArrayList<String> arry_minutes = new ArrayList<String>();
    }

    private ListView lv;

    public void setLv(ListView lv) {
        this.lv = lv;
    }

    public ChargeModeTimeAdapter(List list, Context context) {
        super(list, context);
    }

    @Override
    public void getView(final int position, CommonViewHolder viewHolder) {
        final ViewHolder holder = (ViewHolder) viewHolder;
        ChargeModeTimeItem item = datas.get(position);
        holder.charge_mode_time_top_tv1.setText(item.week);
        holder.charge_mode_time_top_tv2.setText(item.hour + ":" + item.minute);
        if (item.selected) {
            holder.charge_mode_time_top_iv1.setImageResource(R.drawable.gray_arrow_up);
            holder.charge_mode_time_top_bottom_line.setVisibility(View.GONE);
        } else {
            holder.charge_mode_time_top_iv1.setImageResource(R.drawable.gray_arrow_down);
            holder.charge_mode_time_top_bottom_line.setVisibility(View.VISIBLE);
        }
        if (retractPosition == position) {
            item.hour = holder.selectHour;
            item.minute = holder.selectMinute;
        }
        if (holder.mHourAdapter == null) {
            initElements(position, holder);
        }
        if (position == retractPosition || position == collapsePosition) {
            refreshItems(position, holder);
        }
        // refreshItems(position, holder);
        if (Build.VERSION.SDK_INT < 11 || !clicked) {
            if (item.selected) {
                holder.charge_mode_time_wv_layout.setVisibility(View.VISIBLE);
            } else {
                holder.charge_mode_time_wv_layout.setVisibility(View.GONE);
            }
        } else {
            if (retractPosition == position) {
                retractPosition = -1;
                if (wvHeight == 0) {
//						wvHeight = holder.charge_mode_time_wv_layout.getMeasuredHeight();
                    wvHeight = (int) (160 * context.getResources().getDisplayMetrics().density);
                }
                showViewByAnimation(holder.charge_mode_time_wv_layout, false);
            }
            if (collapsePosition == position) {
                holder.charge_mode_time_wv_layout.setVisibility(View.VISIBLE);
                collapsePosition = -1;
                if (wvHeight == 0) {
//						wvHeight = holder.charge_mode_time_wv_layout.getMeasuredHeight();
                    wvHeight = (int) (160 * context.getResources().getDisplayMetrics().density);
                }
                holder.charge_mode_time_wv_layout.setTag(position);
                showViewByAnimation(holder.charge_mode_time_wv_layout, true);
            }
        }
        holder.charge_mode_time_wv_hour.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {
//					if(isHourScroll) {
////						holder.charge_mode_time_wv_hour.setEnabled(false);
//						return ;
//					}else {
//						isHourScroll = true;
//					}
            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
//					if(isHourScroll) {
//						holder.charge_mode_time_wv_minute.setEnabled(true);
//						isHourScroll = false;
                ChargeModeTimeItem timeItem = datas.get(position);
                String hourText = timeItem.hour;
                String minuteText = timeItem.minute;
                if (holder.mHourAdapter != null) {
                    hourText = (String) holder.mHourAdapter.getItemText(wheel.getCurrentItem());
                }
                if (holder.mMinuteAdapter != null) {
                    minuteText = (String) holder.mMinuteAdapter.getItemText(holder.charge_mode_time_wv_minute.getCurrentItem());
                }
                holder.charge_mode_time_wv_hour.setCurrentItem(holder.arry_hours.indexOf(hourText));
                holder.charge_mode_time_wv_minute.setCurrentItem(holder.arry_minutes.indexOf(minuteText));
                holder.charge_mode_time_top_tv2.setText(hourText + ":" + minuteText);

                timeItem.hour = hourText;
                timeItem.minute = minuteText;
                datas.remove(position);
                datas.add(position, timeItem);
//					}
            }
        });
        holder.charge_mode_time_wv_minute.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {
//					if(isMinuteScroll) {
//						holder.charge_mode_time_wv_minute.setEnabled(false);
//					}else {
//						isMinuteScroll = true;
//					}
            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
//					if(isMinuteScroll) {
//						holder.charge_mode_time_wv_minute.setEnabled(true);
//						isMinuteScroll = false;
                ChargeModeTimeItem timeItem = datas.get(position);
                String hourText = timeItem.hour;
                String minuteText = timeItem.minute;
                if (holder.mMinuteAdapter != null) {
                    minuteText = (String) holder.mMinuteAdapter.getItemText(wheel.getCurrentItem());
                }
                if (holder.mHourAdapter != null) {
                    hourText = (String) holder.mHourAdapter.getItemText(holder.charge_mode_time_wv_hour.getCurrentItem());
                }
                holder.charge_mode_time_wv_hour.setCurrentItem(holder.arry_hours.indexOf(hourText));
                holder.charge_mode_time_wv_minute.setCurrentItem(holder.arry_minutes.indexOf(minuteText));
                holder.charge_mode_time_top_tv2.setText(hourText + ":" + minuteText);

                timeItem.hour = hourText;
                timeItem.minute = minuteText;
               datas.remove(position);
               datas.add(position, timeItem);
//					}
            }
        });

        // holder.cancle_tv.setOnClickListener(new OnClickListener() {
        //
        // @Override
        // public void onClick(View v) {
        //
        // }
        // });
        //
        // holder.confirm_tv.setOnClickListener(new OnClickListener() {
        //
        // @Override
        // public void onClick(View v) {
        // BusinessUtil.sendReportByClickType(parent,
        // FunctionNameFindId.PhevSaveTime.getStringValue());
        // }
        // });
    }

    private void refreshItems(int position, final ViewHolder viewHolder) {
        ChargeModeTimeItem item = datas.get(position);
        if (item.selected) {
            viewHolder.charge_mode_time_wv_hour.setCurrentItem(viewHolder.arry_hours.indexOf(item.hour));
            viewHolder.charge_mode_time_wv_minute.setCurrentItem(viewHolder.arry_minutes.indexOf(item.minute));
        } else {
            viewHolder.charge_mode_time_top_tv2.setText(item.hour + ":" + item.minute);
        }
    }

    private void initElements(int position, final ViewHolder viewHolder) {
        initHours(viewHolder);
        initMinutes(viewHolder);
        ChargeModeTimeItem item = datas.get(position);
        viewHolder.mHourAdapter = new CalendarTextAdapter(context, viewHolder.arry_hours,
                viewHolder.arry_hours.indexOf(item.hour), viewHolder.charge_mode_time_wv_hour,
                R.layout.discover_charge_calendar_left);
        viewHolder.charge_mode_time_wv_hour.setShadowsColors(SHADOWS_COLORS);
        viewHolder.charge_mode_time_wv_hour.setVisibleItems(5);
        viewHolder.charge_mode_time_wv_hour.setCyclic(true);
        viewHolder.charge_mode_time_wv_hour.setCenterDrawable(context.getResources().getDrawable(R.drawable.layer_list));
        viewHolder.charge_mode_time_wv_hour.invalidate();
        viewHolder.charge_mode_time_wv_hour.setViewAdapter(viewHolder.mHourAdapter);
        viewHolder.mMinuteAdapter = new CalendarTextAdapter(context, viewHolder.arry_minutes,
                viewHolder.arry_minutes.indexOf(item.minute), viewHolder.charge_mode_time_wv_minute,
                R.layout.discover_charge_calendar_right);
        viewHolder.charge_mode_time_wv_minute.setShadowsColors(SHADOWS_COLORS);
        viewHolder.charge_mode_time_wv_minute.setVisibleItems(5);
        viewHolder.charge_mode_time_wv_minute.setCyclic(true);
        viewHolder.charge_mode_time_wv_minute.setCenterDrawable(context.getResources().getDrawable(R.drawable.layer_list));
        viewHolder.charge_mode_time_wv_minute.invalidate();
        viewHolder.charge_mode_time_wv_minute.setViewAdapter(viewHolder.mMinuteAdapter);
        viewHolder.charge_mode_time_wv_hour.addChangingListener(new OnWheelChangedListener() {

            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                // TODO Auto-generated method stub
                String currentText = (String) viewHolder.mHourAdapter.getItemText(wheel.getCurrentItem());
                viewHolder.selectHour = currentText;
                setTextviewSize(wheel, viewHolder.mHourAdapter);
            }
        });
        viewHolder.charge_mode_time_wv_minute.addChangingListener(new OnWheelChangedListener() {

            @Override
            public void onChanged(WheelView wheel, int oldValue, int newValue) {
                // TODO Auto-generated method stub
                String currentText = (String) viewHolder.mMinuteAdapter.getItemText(wheel.getCurrentItem());
                viewHolder.selectMinute = currentText;
                setTextviewSize(wheel, viewHolder.mMinuteAdapter);
            }
        });
        viewHolder.mMinuteAdapter.wheelView = viewHolder.charge_mode_time_wv_minute;
        viewHolder.mHourAdapter.wheelView = viewHolder.charge_mode_time_wv_hour;
    }

    private void initHours(ViewHolder viewHolder) {
        viewHolder.arry_hours.clear();
        for (int i = 0; i < 24; i++) {
            viewHolder.arry_hours.add(StringUntil.prefixZero(i, 2));
        }
    }

    private void initMinutes(ViewHolder viewHolder) {
        viewHolder.arry_minutes.clear();
        viewHolder.arry_minutes.add("00");
        viewHolder.arry_minutes.add("15");
        viewHolder.arry_minutes.add("30");
        viewHolder.arry_minutes.add("45");
    }

    /**
     * 设置字体大小
     *
     * @param adapter
     */
    private void setTextviewSize(WheelView wheel, CalendarTextAdapter adapter) {
        ArrayList<TextView> arrayList = adapter.getTestViews();
        for (int i = 0; i < arrayList.size(); i++) {
            TextView view = arrayList.get(i);
            if (((Integer) view.getTag()) == wheel.getCurrentItem()) {
                view.setTextSize(maxTextSize);
            } else if (Math.abs((Integer) view.getTag() - wheel.getCurrentItem()) == 1
                    || adapter.list.size() - Math.abs((Integer) view.getTag() - wheel.getCurrentItem()) == 1) {
                view.setTextSize((maxTextSize + minTextSize) / 2.0f);
            } else if (Math.abs((Integer) view.getTag() - wheel.getCurrentItem()) == 2
                    || adapter.list.size() - Math.abs((Integer) view.getTag() - wheel.getCurrentItem()) == 2) {
                view.setTextSize(minTextSize);
            } else {
                view.setTextSize(minTextSize);
            }
        }
    }

    private void showViewByAnimation(final View view, final boolean show) {
        if (Build.VERSION.SDK_INT >= 11) {
            ValueAnimator anim;
            final int endVal;
            if (show) {
                endVal = wvHeight;
                anim = ValueAnimator.ofInt(0, endVal);
            } else {
                endVal = 0;
                anim = ValueAnimator.ofInt(wvHeight, endVal);
            }
            anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator valueAnimator) {
                    int val = (Integer) valueAnimator.getAnimatedValue();
                    ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
                    layoutParams.height = val;
                    view.setLayoutParams(layoutParams);
                    if (show && !doubleAnim) {
                        float displayY = ((View) (view.getParent())).getY() + view.getY() + val;
                        checkHeight(displayY,lv);
                    }
                }
            });
            anim.setDuration(500);
            anim.start();
        }
    }

    public void checkHeight(float displayY,ListView lv){
        if (displayY > lv.getHeight()) {
            // charge_mode_time_lv.setSelectionFromTop((Integer)
            // view.getTag(), (int) (view.getY() + val));
            HacksUtils.scrollListBy(lv,
                    (int) (displayY - lv.getHeight()));
        }
    }

    @Override
    public int layoutId() {
        return R.layout.charge_mode_time_item;
    }

    @Override
    public CommonViewHolder getViewHolder() {
        return new ViewHolder();
    }

    private class CalendarTextAdapter extends AbstractWheelTextAdapter {
        ArrayList<String> list;
        WheelView wheelView;

        // private int[] SHADOWS_COLORS = new int[]{0xffffffff, 0xffffffff,
        // 0xffffffff};

        protected CalendarTextAdapter(Context context, ArrayList<String> list, int currentItem, WheelView wheelView,
                                      int layoutId) {
            super(context, layoutId, NO_RESOURCE, currentItem, maxTextSize, minTextSize);
            this.list = list;
            this.wheelView = wheelView;
            setItemTextResource(R.id.charge_mode_time_item_calendar);
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            View view = super.getItem(index, cachedView, parent);
            setTextviewSize(wheelView, this);
            return view;
        }

        @Override
        public int getItemsCount() {
            return list.size();
        }

        @Override
        protected CharSequence getItemText(int index) {
            return list.get(index) + "";
        }
    }

}
